import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Spin, Space, Card, Typography, Divider } from 'antd';
import { useLog } from '../../hooks/useLog';
import { LogCategories, LogGroups } from './logConfig';

const { Title, Paragraph, Text } = Typography;

interface FormData {
  username: string;
  email: string;
}

const LogSystemDemo: React.FC = () => {
  const [form] = Form.useForm<FormData>();
  const { logCategory, categoryGroup } = useLog();
  const [loading, setLoading] = useState(false);

  // ------------------ 配置状态 ------------------
  const [configState, setConfigState] = useState({
    categories: logCategory.getAllRegisteredCategories(),
    groups: categoryGroup.getAllGroups()
  });

  const refreshConfig = (title?: string) => {
    setConfigState({
      categories: logCategory.getAllRegisteredCategories(),
      groups: categoryGroup.getAllGroups()
    });
    if (title) {
      console.group(`🔧 ${title}`);
      console.log('已注册分类:', logCategory.getAllRegisteredCategories());
      console.log('已注册分组:', categoryGroup.getAllGroups());
      console.groupEnd();
    }
  };

  // ------------------ 初始化 ------------------
  useEffect(() => {
    categoryGroup.enableGroups([LogGroups.UI_FLOW]);
    refreshConfig('初始化配置状态');
  }, []);

  // ------------------ 单项控制（支持多选） ------------------
  const toggleCategory = (name: string) => {
    const cat = configState.categories[name];
    if (!cat) return;
    if (cat.active) logCategory.disableCategories([name]);
    else logCategory.enableCategories([name]);
    refreshConfig(`切换分类 ${name}`);
  };

  const toggleGroup = (name: string) => {
    const grp = configState.groups[name];
    if (!grp) return;
    if (grp.active) categoryGroup.disableGroups([name]);
    else categoryGroup.enableGroups([name]);
    refreshConfig(`切换分组 ${name}`);
  };

  // ------------------ 表单操作 ------------------
  const fetchData = async () => {
    logCategory.group('请求数据', [LogCategories.API, LogCategories.INPUT]);
    logCategory.info('开始请求用户数据', LogCategories.API);

    return new Promise<FormData>((resolve) => {
      setTimeout(() => {
        const data = { username: 'Alice', email: 'alice@example.com' };
        logCategory.info('数据请求完成', LogCategories.API, data);
        resolve(data);
      }, 1000);
    }).finally(() => logCategory.groupEnd());
  };

  const preprocessData = (data: FormData) => {
    logCategory.group('数据预处理', [LogCategories.EFFECT, LogCategories.INPUT]);
    logCategory.debug('开始处理数据', LogCategories.EFFECT);

    const processed = { ...data, username: data.username.toUpperCase() };
    logCategory.info('数据预处理完成', LogCategories.EFFECT, processed);

    logCategory.groupEnd();
    return processed;
  };

  const handleSave = async () => {
    logCategory.group('保存表单', [LogCategories.API, LogCategories.INPUT]);
    logCategory.info('用户点击保存', LogCategories.CLICK);

    const values = form.getFieldsValue();
    logCategory.debug('表单值', LogCategories.INPUT, values);

    logCategory.info('提交到 API', LogCategories.API);
    await new Promise((resolve) => setTimeout(resolve, 800));
    logCategory.info('保存完成', LogCategories.API);

    logCategory.groupEnd();
  };

  // ------------------ 日志测试 ------------------
  const testLogs = () => {
    Object.keys(configState.categories).forEach((catName) => {
      logCategory.debug(`分类日志 DEBUG: ${catName}`, [catName]);
      logCategory.info(`分类日志 INFO: ${catName}`, [catName]);
    });

    Object.keys(configState.groups).forEach((groupName) => {
      const cats = Object.keys(categoryGroup.getGroup(groupName)?.categories || {});
      logCategory.group(`${groupName} 分组日志`, cats, () => {
        logCategory.info('分组内日志1', cats);
        logCategory.debug('分组内日志2', cats);
      });
    });
  };

  // ------------------ 模拟表单操作 ------------------
  const runDemoFlow = async () => {
    setLoading(true);

    logCategory.info('模拟表单操作: 表单初始化开始', [LogCategories.MOUNT]);
    const data = await fetchData();
    const processed = preprocessData(data);
    form.setFieldsValue(processed);
    logCategory.info('模拟表单操作: 表单初始化完成', [LogCategories.MOUNT]);

    logCategory.info('模拟表单操作: 模拟用户修改表单', [LogCategories.INPUT]);
    form.setFieldsValue({ username: 'Bob', email: 'bob@example.com' });
    logCategory.info('模拟表单操作: 用户修改完成', [LogCategories.INPUT]);

    logCategory.info('模拟表单操作: 保存表单', [LogCategories.CLICK]);
    await handleSave();

    logCategory.info('模拟表单操作: 日志输出测试', [LogCategories.EFFECT]);
    testLogs();

    setLoading(false);
  };

  // ------------------ 渲染状态 ------------------
  const renderStatus = () => {
    const { categories, groups } = configState;

    const buttonStyle = (active: any) => ({
      backgroundColor: active ? '#f6ffed' : '#fff2f0'
    });

    return (
      <div style={{ marginTop: 20 }}>
        <h3>分类状态（可多选）</h3>
        <Space wrap>
          {Object.entries(categories).map(([name, cfg]) => (
            <Button
              key={name}
              size="small"
              style={buttonStyle(cfg.active)}
              onClick={() => toggleCategory(name)}
            >
              {name}
            </Button>
          ))}
        </Space>
        <Divider />
        <h3>分组状态（可多选）</h3>
        <Space wrap>
          {Object.entries(groups).map(([name, cfg]) => (
            <Button
              key={name}
              size="small"
              style={buttonStyle(cfg.active)}
              onClick={() => toggleGroup(name)}
            >
              {name}
            </Button>
          ))}
        </Space>
      </div>
    );
  };

  return (
    <div style={{ padding: 20 }}>
      {/* ------------------ Demo说明 ------------------ */}
      <Card style={{ marginBottom: 20 }}>
        <Title level={4}>日志系统 Demo 演示说明</Title>
        <Paragraph>
          本 Demo
          演示了一个日志系统在表单中的使用，包括分类日志、分组日志、分组内分类日志，以及批量操作。
        </Paragraph>
        <Paragraph>
          <Text strong>功能：</Text>
          <ul>
            <li>表单初始化（fetch + preprocess）</li>
            <li>用户修改表单</li>
            <li>保存表单</li>
            <li>日志输出分类/分组/分组内分类</li>
            <li>单独控制分类和分组启用状态（支持多选）</li>
            <li>批量启用/禁用分类和分组</li>
            <li>模拟表单操作按钮，一次性模拟完整流程（初始化、更新表单）</li>
            <li>初始化：请求数据→预处理数据</li>
            <li>更新表单：修改表单→点击保存</li>
          </ul>
        </Paragraph>
      </Card>

      <h1>日志系统模拟表单操作 Demo</h1>
      <Spin spinning={loading}>
        <Form form={form} layout="vertical">
          <Form.Item label="用户名" name="username">
            <Input onChange={() => logCategory.info('修改用户名', LogCategories.INPUT)} />
          </Form.Item>
          <Form.Item label="邮箱" name="email">
            <Input onChange={() => logCategory.info('修改邮箱', LogCategories.INPUT)} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={handleSave}>
              保存
            </Button>
          </Form.Item>
        </Form>

        {/* ------------------ 批量控制按钮 ------------------ */}
        <div style={{ marginTop: 20 }}>
          <Space wrap>
            <Button
              onClick={() => {
                logCategory.enableAll();
                refreshConfig('启用所有分类');
              }}
            >
              启用所有分类
            </Button>
            <Button
              onClick={() => {
                logCategory.disableAll();
                refreshConfig('禁用所有分类');
              }}
              danger
            >
              禁用所有分类
            </Button>
            <Button
              onClick={() => {
                categoryGroup.enableAll();
                refreshConfig('启用所有分组');
              }}
            >
              启用所有分组
            </Button>
            <Button
              onClick={() => {
                categoryGroup.disableAll();
                refreshConfig('禁用所有分组');
              }}
              danger
            >
              禁用所有分组
            </Button>
          </Space>
        </div>

        {/* ------------------ 模拟表单操作按钮 ------------------ */}
        <div style={{ marginTop: 20 }}>
          <Button type="primary" onClick={runDemoFlow}>
            模拟表单操作
          </Button>
        </div>

        {/* ------------------ 单项控制按钮 ------------------ */}
        {renderStatus()}
      </Spin>
    </div>
  );
};

export default LogSystemDemo;
